<?php

/**
 * 使用示例
 * @author M2
 * @version 1.0
 * create Date 2013-11-4
 * update Date 2013-11-5
 * update Date 2013-11-6
 * <yl:contents><yl:content type="title"/></yl:contents>
 */
class YlContentsTaglib {
    /**
     * 表前缀，默认为 yl_
     * @access private
     * @var string 
     */
    private $_dbPrefix = 'yl_';

    public function __construct() {
        C(include SITE_PATH . '/extends/taglib/tagarr.php');
        $dbPrefix = C('DB_PREFIX');
        !empty($dbPrefix) && $this->_dbPrefix = $dbPrefix;
    }

    /**
     * 解析<yl:contents>标签
     * @param string $content 需要解析的内容
     * @param int $sid 站点id
     * @param array $cates 当前栏目的所有信息
     * @param string $domain 域名
     * @param array $channel 全局配置（其实外面是changestyle）
     * @param int $contentid 内容id
     * @return string 解析后的内容
     */
    public function parse($content, $sid, $cates, $domain, $channel,$contentid=0) {
        if (stripos($content, 'yl:contents') !== false) {
            $matches = preg_parse($content, 'yl:contents');
            foreach ($matches as $match) {
                $parseStr = '';
                //where条件中可能含有'<','>'等特殊字符，先去掉
                $where = getParseOneAttr($match, 'where');
                $contentText = str_replace($where, '', $match);
                
                $attrString = getParseAttrString($contentText, 'yl:contents');
                $contentText = getParseContentText($contentText, 'yl:contents');
                
                
                $limit = getParseOneAttr($attrString, 'limit');
                $startnum = getParseOneAttr($attrString, 'startnum');
                $order = getParseOneAttr($attrString, 'order');
                $channelname = getParseOneAttr($attrString, 'channelname');
                $scope = getParseOneAttr($attrString, 'scope');
                $groupchannel = getParseOneAttr($attrString, 'groupchannel');
                $groupchannelnot = getParseOneAttr($attrString, 'groupchannelnot');
                $groupcontent = getParseOneAttr($attrString, 'groupcontent');
                $groupcontentnot = getParseOneAttr($attrString, 'groupcontentnot');
                $join = getParseOneAttr($attrString, 'join');
                $isimage = getParseOneAttr($attrString, 'isimage');
                $istop = getParseOneAttr($attrString, 'istop');
                $isrecommend = getParseOneAttr($attrString, 'isrecommend');
                $iscolor = getParseOneAttr($attrString, 'iscolor');
                $ishot = getParseOneAttr($attrString, 'ishot');

                $limits = $limit ? $limit : 10;
                $startNum = $startnum ? $startnum : 0;
                $order = !empty($order) ? $order . ' desc' : 'updatetime desc';
                $data = $this->_dbPrefix.'cms_article.siteid = ' . $sid;
                
                !empty($join) ? $join : ' ';
                //替换$where中的{}标签
                $where = $this->parseBraces($where,$cates,$sid,$domain,$contentid);
                //替换$groupchannel中的{}标签
                $groupchannel = $this->parseBraces($groupchannel, $cates, $sid, $domain, $contentid);
                
               if (!empty($channelname)) {
                    //$cates['id'] = M('cms_category')->where('siteid = '.$sid.' and cname="'.$e->channelname.'"')->getField('id');
                    //update next 2013-12-11 增加单栏目标签缓存
                    if (($arrcategory = S('cache_channelname_' . $sid . '_' . $channelname)) === false) {
                        $arrcategory = M('cms_category')
                                ->field('(case when url <> "" then url when createurl <> "" then createurl
	                            else (concat("' . $domain . '","/",replace(replace((case when catenaming <> ""
	                		 then catenaming else ("' . $channel['catenaming'] . '") end),"{cateid}",id),"{@ChannelID}",id))) end) as url,
	                            replace(imageurl,"@","' . $domain . '") as imageurl,id,cname,content,keywords,
	                            description')
                                ->where('siteid = ' . $sid . ' and cname="' . $channelname . '"')
                                ->find();
                        S('cache_channelname_' . $sid . '_' . $channelname, $arrcategory);
                    }
                    $cates['id'] = $arrcategory['id'];
                }

                $artnamingsql = '"' . $channel['artnaming'] . '"';
                $artnamingid = "";
                
                if(empty($groupchannel)){
                    if ($scope) {
                        if (strtolower($scope) === 'all') {
                            if(false === ($gcate = S('cache_childcate_'.$cates['id']))){
                                $gcate = D('Category')->getChildCate($cates['id']);
                                S('cache_childcate_'.$cates['id'], $gcate, 24*3600);
                            }
                            $data .= ' and FIND_IN_SET( cid, "' . $gcate . '" )';

                            //是否只有一个栏目ID,就保存起来
                            if (strpos($gcate, ',') <= 0) {
                                $artnamingid = $gcate;
                            }
                        }
                    } else {
                        $data .= ' and cid=' . $cates['id'];
                        //只有一个栏目ID,就保存起来
                        $artnamingid = $cates['id'];
                    }
                }else{
                    $data .=" AND INSTR((select CONCAT(',',w.group_name_collection,',') FROM ".$this->_dbPrefix."cms_category w WHERE w.id=cid),'," . $groupchannel . ",')>0";
                }

                //add next 2013-12-11 增加得到栏目生成内容规划的判断
                if (!empty($artnamingid)) {
                    if ($category_list = S('cache_channel_' . $artnamingid) === false) {
                        $category_list = M('cms_category')->where('id=' . $artnamingid)->find();
                        S('cache_channel_' . $artnamingid, $category_list);
                    }
                    if (!empty($category_list['artnaming'])) {
                        $artnamingsql = '"' . $category_list['artnaming'] . '"';
                    }
                } else {
                    $artnamingsql = '(select (case when B.artnaming <> "" then B.artnaming else ("' . $channel['artnaming'] . '") end) from '.$this->_dbPrefix.'cms_category B where B.id=cid)';
                }

                //add next 2013-12-09 增加内容列表项中栏目分组与内容分组
                if (!empty($groupchannelnot)) {
                    $data .=" AND INSTR((select CONCAT(',',w.group_name_collection,',') FROM ".$this->_dbPrefix."cms_category w WHERE w.id=cid),'," . $groupchannelnot . ",')<=0";
                }
                if (!empty($groupcontent)) {
                    $data .= " and INSTR(CONCAT(',',group_name_collection,','),'," . $groupcontent . ",')>0";
                }
                if (!empty($groupcontentnot)) {
                    $data .= " and INSTR(CONCAT(',',group_name_collection,','),'," . $groupcontentnot . ",')<=0";
                }
                //---

                if ($where) {
                    $data .= ' and ' . $where;
                }
                if (isset($isimage) && !empty($isimage)) {
                    if ($isimage === 'true') {
                        $data .= ' and imageurl <> ""';
                    }
                }
                if (isset($istop) && !empty($istop)) {
                    if ($istop === 'false') {
                        $data .= ' and is_top=0';
                    } elseif ($istop === 'true') {
                        $data .= ' and is_top=1';
                    }
                }
                if (isset($isrecommend) && !empty($isrecommend)) {
                    if ($isrecommend === 'true') {
                        $data .= ' and is_recommend=1';
                    } elseif ($isrecommend === 'false') {
                        $data .= ' and is_recommend=0';
                    }
                }
                if (isset($iscolor) && !empty($iscolor)) {
                    if ($iscolor === 'true') {
                        $data .= ' and is_color=1';
                    } elseif ($iscolor === 'false') {
                        $data .= ' and is_color=0';
                    }
                }
                if (isset($ishot) && !empty($ishot)) {
                    if ($ishot === 'true') {
                        $data .= ' and is_hot=1';
                    } elseif ($ishot === 'false') {
                        $data .= ' and is_hot=0';
                    }
                }
                
                
                //OOO add by jepin 141120
                if(empty($join)){
                  $idsstr=pidsO();
                  $data.=$idsstr;
                }
                //OOO end
                // update jepin  2014-09-01 新增articledate 列
                $list = M()->query('select (case when url <> "" then url else
    (concat("' . $domain . '","/",replace(replace(' . $artnamingsql . ',
    "{cateid}",cid),"{contentid}",'.$this->_dbPrefix.'cms_article.id))) end) as url,
     replace(imageurl,"@","' . $domain . '") as imageurl,replace(big_imageurl,"@","' . $domain . '") as big_imageurl,title,
     subtitle,author,updatetime,inputtime,tags,articledate,comment_count,
     source,content,readpoint,keywords,cid,'.$this->_dbPrefix.'cms_article.id,'.$this->_dbPrefix.'cms_article.siteid,description,create_uid,create_uname,update_uid,summary,group_name_collection,
     update_uname,fileurl,@row := @row + 1 as ItemIndex from (select @row := 0) r,'.$this->_dbPrefix.'cms_article '.$join.' where status =1 and ' . $data . ' order by ' . $order . ' limit ' . $startNum . ',' . $limits);
                unset($data);
               //OOO add by jepin 141120
               if(empty($join)){
               	if (!empty($list)) {
               		$i=0;
               		$newids= array();
               		foreach ( $list as $v){
               			$newids[$i] =$v['id'];
               			$i++;
               		}
               		pidsI($newids);
               	}
               }
               //OOO end
               
                if (!empty($list)) {
                    foreach ($list as $k => $v) {
                        S('cache_contents_' . $v['id'], $v);
                        //update next 2013-12-12 简化替换操作
                        $text = taglib(C('yl:if'))->parse($contentText, $v);
                        $text = taglib(C('yl:a'))->parse($text, $sid, $v, '1', $domain, $channel);
                        $text = taglib(C('yl:content'))->parse($text, $v, $domain);
                        $text = taglib(C('yl:image'))->parse($text, $v);
                        $text = taglib(C('yl:count'))->parse($text, $v);

                        if (strpos($text, '{') && strpos($text, '}')) {
                            preg_match_all('/\{Content\.(.*?)\}/eis', $text, $out);
                            for ($i = 0; $i < count($out[1]); $i++) {
                                $text = str_ireplace($out[0][$i], $v[$out[1][$i]], $text);
                            }
                        }
                        $parseStr .= $text;
                    }
                } else {
                    $parseStr = '';
                }
                $content = str_replace($match, $parseStr, $content);
            }
        }
        return $content;
    }
    
    /**
     * 替换内容
     */
    private function parseBraces($content,$cates,$sid,$domain,$contentid){
        if (strpos($content, '{') && strpos($content, '}')) {
            $content = str_replace('{site.id}', $sid, $content);
            $content = str_replace('{site.domain}', $domain, $content);
            preg_match_all('/\{Channel\.(.*?)\}/eis', $content, $match);
            for ($i = 0; $i < count($match[1]); $i++) {
                $content = str_ireplace($match[0][$i], $cates[$match[1][$i]], $content);
            }
            $content = str_replace('{Content.id}', $contentid, $content);
            return $content;
        }
        return $content;
    }

}
